from docx import Document
from docx.shared import Pt

def replace_text_in_paragraphs(paragraphs, search_text, replace_text):
    for paragraph in paragraphs:
        if search_text in paragraph.text:
            inline = paragraph.runs
            for item in inline:
                if search_text in item.text:
                    item.text = item.text.replace(search_text, replace_text)

# 打开现有的word文档
document = Document("example.docx")

search_text = "old text"
replace_text = "new text"

# 替换正文中的文本
for paragraph in document.paragraphs:
    replace_text_in_paragraphs([paragraph], search_text, replace_text)

# 替换页眉中的文本
for section in document.sections:
    header = section.header
    for paragraph in header.paragraphs:
        replace_text_in_paragraphs([paragraph], search_text, replace_text)

# 保存更改后的文档 
document.save('modified_example.docx')